package com.settlement.system.common.util.common;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;


import com.google.common.net.UrlEscapers;

/**
 * @author author
 */
@Slf4j
public class AcsFileUtils {

	private static RequestConfig requestConfig;
	private static CloseableHttpClient client = HttpClientBuilder.create().build();

	public static final String SYSTEM_NAME = "retail";

	public static final String SUB_SYSTEM_NAME = "acs";

	public static final String STATIC_REPORT_MOUDLE = "uploadfile";

	public static String getStaticReportPath(String fileName) {
		// return FileUtil.getPathPrefix(SYSTEM_NAME, SUB_SYSTEM_NAME, STATIC_REPORT_MOUDLE).concat(fileName);
		return null;
	}

	public static String getStaticReportPath() {
		// return FileUtil.getPathPrefix(SYSTEM_NAME, SUB_SYSTEM_NAME, STATIC_REPORT_MOUDLE);
		return null;
	}

	static {
		int timeout = 5 * 1000;
		requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout).setConnectTimeout(timeout)
				.setSocketTimeout(timeout).build();
	}

	/**
	 * 从网络Url获取字节文件
	 *
	 * @param urlStr
	 * @throws IOException
	 */
	public static byte[] getByteDataByUrl(String urlStr) throws IOException {
		log.info("down load file:" + urlStr);
		if (StringUtils.isBlank(urlStr)) {
			return null;
		}
		try {
			return excute(new HttpGet(urlEscaper(urlStr)));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			throw e;
		}
	}

	static byte[] excute(HttpRequestBase request) throws ClientProtocolException, IOException {

		HttpEntity entity = getResponseEntry(request);

		byte[] content = EntityUtils.toByteArray(entity);

		log.debug("query " + request.getURI().toString() + ":" + content);

		return content;

	}

	protected static HttpEntity getResponseEntry(HttpRequestBase request) throws IOException, ClientProtocolException {
		CloseableHttpResponse response = null;
		request.setConfig(requestConfig);

		response = client.execute(request);

		int status = response.getStatusLine().getStatusCode();
		final int httpStatusOk = 200;
		if (status != httpStatusOk) {
			request.abort();
			throw new IOException("调用异常，错误代码:" + status);
		}
		HttpEntity entity = response.getEntity();
		return entity;
	}

	static InputStream excuteStream(HttpRequestBase request) throws ClientProtocolException, IOException {
		HttpEntity entity = getResponseEntry(request);
		return entity.getContent();
	}

	/**
	 * 从网络Url获取流
	 *
	 * @param urlStr
	 * @throws IOException
	 */
	public static File writeLocalFileByUrl(String urlStr, String localPath) throws IOException {
		InputStream in = null;
		File file = new File(localPath);
		log.info("Write Local File By Url:" + urlStr);
		try {
			in = excuteStream(new HttpGet(urlEscaper(urlStr)));
			inputStreamToFile(in, file);
			return file;
		} finally {
			if (null != in) {
				in.close();
			}
		}
	}

	public static void inputStreamToFile(InputStream ins, File file) throws IOException {
		final int bufferSize = 8192;
		OutputStream os = new FileOutputStream(file);
		int bytesRead = 0;
		byte[] buffer = new byte[bufferSize];
		try {
			while ((bytesRead = ins.read(buffer, 0, bufferSize)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
		} finally {
			if (null != os) {
				if (null != os) {
					os.close();
				}
				if (null != ins) {
				}
				if (null != ins) {
					ins.close();
				}
			}

		}
	}

		/**
		 * 获取字节数组
		 *
		 * @param inputStream
		 * @return
		 * @throws IOException
		 */
		public static byte[] readInputStream (InputStream inputStream) throws IOException {
			if (inputStream == null) {
				return null;
			}
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			try {
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = inputStream.read(buffer)) != -1) {
					bos.write(buffer, 0, len);
				}
			} catch (IOException e) {
				throw e;
			} finally {
				bos.close();
			}
			return bos.toByteArray();
		}

		private static String urlEscaper (String url){
			int index = url.lastIndexOf('/');
			String first = url.substring(0, index);
			String last = url.substring(index);

			last = UrlEscapers.urlPathSegmentEscaper().escape(last);

			return first + "/" + last;
		}


		public static String getExportReportQueryExcel (String fileName){
			/*String specialPath = "reportexport/" + DateUtil.getYear(new Date()) + "/" + DateUtil.getMonth(new Date())
					+ "/" + DateUtil.getDay(new Date());
			return FileUtil.getPathPrefix(SYSTEM_NAME, SUB_SYSTEM_NAME, specialPath).concat(fileName);*/
			return null;
		}

}
